package com.aviator.detective.execute.eventbus;

import com.aviator.detective.common.reflect.JavassistUtil;
import com.aviator.detective.execute.listener.Listener;
import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import javassist.CannotCompileException;
import javassist.NotFoundException;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 利用guava event bus做事件总线，将：Listener上所有事件方法加上
 */
public class EventBusAnnotationRegistry {

    private final List<Listener> listeners = new ArrayList<>();

    public void registerListeners(List<Listener> listeners){
        listeners.addAll(listeners);
    }

    public List<Listener> getListeners(){
        return this.listeners;
    }

    public void registerAnnotation() throws IOException, CannotCompileException, NotFoundException {
        for (Listener listener: listeners){
            AllSubscribe allSubscribe = listener.getClass().getAnnotation(AllSubscribe.class);
            if (allSubscribe != null) {
                Method[] methods = listener.getClass().getDeclaredMethods();
                for (Method method : methods) {
                    method.setAccessible(true);
                    //给方法添加 @Subscribe 和 AllowConcurrentEvents注解
                    JavassistUtil.addAnnotationOnAllMethod(listener.getClass().getName(), Subscribe.class);
                    AllAllowConcurrentEvents allowConcurrentEvents = listener.getClass().getAnnotation(AllAllowConcurrentEvents.class);
                    if (allowConcurrentEvents !=null){
                        JavassistUtil.addAnnotationOnAllMethod(listener.getClass().getName(), AllowConcurrentEvents.class);
                    }
                }
            }
        }
    }

}
